<script setup lang="ts">
import { ref, computed, onMounted, nextTick } from 'vue';
import { Page } from '@vben/common-ui';
import {
  getPatientInfo,
  timelineEventInfo,
  latestVitalsInfo,
} from '#/api/patient/manage';
import type {
  ManageVO,
  PatientHealthData,
  TimeEventLine,
} from '#/api/patient/manage/model';
import { renderDict } from '#/utils/render';
import { getAgeByIdCard } from '#/utils/calculate';
import {
  Card,
  Descriptions,
  Tag,
  Tabs,
  Button,
  Space,
  theme,
} from 'ant-design-vue';
import { UserOutlined, EditOutlined } from '@ant-design/icons-vue';
import { Vue3SeamlessScroll } from 'vue3-seamless-scroll';
import { useRoute } from 'vue-router';
const route = useRoute();
const enrollmentId = route.params.id as string;
const { token } = theme.useToken();
const patientInfo = ref<ManageVO>({} as ManageVO);

// const currentData = {
//   bloodGlucose: '6.8 mmol/L',
//   mealBloodGlucose: '6.8 mmol/L',
//   height: '170 cm',
//   bmi: 26,
//   weight: '80 kg',
// };

const currentData = ref<PatientHealthData>({} as PatientHealthData);

const interventionPoints = ref<TimeEventLine[]>([]);

const activeTabKey = ref('path-tracking');
const getInterventionPoints = async () => {
  const data = {
    patientEnrollmentId: enrollmentId,
  };
  await nextTick();
  interventionPoints.value = await timelineEventInfo(data);
};
getInterventionPoints();
const getLatestVitals = async () => {
  currentData.value = await latestVitalsInfo(patientInfo.value.patientUserId);
};

// 每行显示的节点数量
const nodesPerRow = 5;

// 每行显示的节点数量保持不变，用于模板中的计算

const getPatientData = async () => {
  patientInfo.value = await getPatientInfo(enrollmentId);
};
onMounted(async () => {
  await getPatientData();
  await getLatestVitals();
});
</script>

<template>
  <Page :auto-content-height="true">
    <div class="flex h-full flex-col p-4">
      <!-- 顶部患者信息栏 -->
      <Card
        :bordered="false"
        :style="{ backgroundColor: token.colorBgContainer }"
      >
        <div class="flex items-start gap-8">
          <div class="flex-shrink-0 text-center">
            <div
              class="mb-2 flex h-24 w-24 items-center justify-center rounded-full bg-gray-200"
            >
              <UserOutlined
                :style="{ fontSize: '48px', color: token.colorTextSecondary }"
              />
            </div>
            <!-- <Button type="link">编辑头像</Button> -->
          </div>

          <div class="flex-grow">
            <div class="mb-4 flex items-center gap-4">
              <h1 class="mb-0 text-2xl font-bold">
                {{ patientInfo.patientName }}
              </h1>
              <h2 class="text-xl font-bold" v-if="patientInfo.sex">
                <component :is="renderDict(patientInfo.sex, 'sys_user_sex')" />
              </h2>
              <h2 class="text-xl font-bold">
                <span>{{ getAgeByIdCard(patientInfo.idCard) }}岁</span>
              </h2>
              <!-- <span>{{ patientInfo.sex }}</span> -->
              <Space>
                <!-- <Tag
                  v-for="tag in patientInfo.tags"
                  :key="tag"
                  :color="getTagColor(tag)"
                  >{{ tag }}</Tag
                > -->
              </Space>
              <!-- <Button type="primary" ghost size="small"
                ><EditOutlined /> 编辑资料</Button
              > -->
            </div>
            <Descriptions :column="1">
              <Descriptions.Item label="身份证号">{{
                patientInfo.idCard
              }}</Descriptions.Item>
              <Descriptions.Item label="患者来源">{{
                patientInfo.source
              }}</Descriptions.Item>
              <Descriptions.Item label="所属项目">{{
                patientInfo.projectName
              }}</Descriptions.Item>
              <Descriptions.Item label="所属实验">{{
                patientInfo.trialName
              }}</Descriptions.Item>
              <Descriptions.Item label="患者分组">{{
                patientInfo.group
              }}</Descriptions.Item>
            </Descriptions>
          </div>

          <div class="flex gap-4">
            <Card size="small" title="当前数据" class="w-[280px]">
              <template #extra
                ><a href="#" class="card-extra-link">更多</a></template
              >
              <Descriptions :column="1" size="small">
                <Descriptions.Item label="血糖"
                  >{{
                    currentData.latestBloodGlucose?.glucoseLevel || ''
                  }}mmol/L</Descriptions.Item
                >
                <Descriptions.Item label="血压"
                  >{{
                    currentData.latestBloodPressure?.systolicPressure || ''
                  }}mmHg /
                  {{
                    currentData.latestBloodPressure?.diastolicPressure || ''
                  }}mmHg</Descriptions.Item
                >
                <Descriptions.Item label="身高"
                  >{{
                    currentData.latestHeightWeight?.heightCm || ''
                  }}cm</Descriptions.Item
                >
                <Descriptions.Item label="体重"
                  >{{
                    currentData.latestHeightWeight?.weightKg || ''
                  }}kg</Descriptions.Item
                >
                <Descriptions.Item label="BMI"
                  >{{
                    currentData.latestHeightWeight?.bmi || ''
                  }}kg/m²</Descriptions.Item
                >
              </Descriptions>
            </Card>
            <Card size="small" title="干预要点" class="w-[280px]">
              <template #extra>
                <!-- <a href="#" class="card-extra-link">更多</a> -->
              </template>
              <div
                class="intervention-list-wrapper"
                v-if="interventionPoints.length > 0"
              >
                <Vue3SeamlessScroll
                  :list="interventionPoints"
                  :step="0.2"
                  :hover="true"
                  :limit-scroll-num="5"
                >
                  <ul class="intervention-list">
                    <li
                      v-for="(item, index) in interventionPoints"
                      :key="index"
                      class="intervention-item"
                    >
                      <span>{{ item.title }}</span>
                      <span class="date">{{ item.eventTimestamp }}</span>
                    </li>
                  </ul>
                </Vue3SeamlessScroll>
              </div>
            </Card>
          </div>
        </div>
      </Card>

      <!-- Tab切换区域 -->
      <Card :bordered="false" class="mt-4 flex-1">
        <Tabs v-model:activeKey="activeTabKey">
          <Tabs.TabPane key="path-tracking" tab="路径跟踪">
            <div class="timeline-container">
              <div class="timeline-track">
                <template
                  v-for="row in Math.ceil(
                    interventionPoints.length / nodesPerRow,
                  )"
                  :key="row"
                >
                  <div
                    class="timeline-row"
                    :class="{ 'row-reverse': (row - 1) % 2 === 1 }"
                  >
                    <template v-for="col in nodesPerRow" :key="col">
                      <div
                        v-if="
                          (row - 1) * nodesPerRow + col - 1 <
                          interventionPoints.length
                        "
                        class="timeline-node"
                      >
                        <div class="timeline-card">
                          <div class="timeline-number">
                            {{ (row - 1) * nodesPerRow + col }}
                          </div>
                          <div class="timeline-date">
                            {{
                              interventionPoints[
                                (row - 1) * nodesPerRow + col - 1
                              ]?.eventTimestamp
                            }}
                          </div>
                          <div class="timeline-title">
                            {{
                              interventionPoints[
                                (row - 1) * nodesPerRow + col - 1
                              ]?.title
                            }}
                          </div>
                          <div
                            v-if="
                              interventionPoints[
                                (row - 1) * nodesPerRow + col - 1
                              ]?.description
                            "
                            class="timeline-content"
                          >
                            {{
                              interventionPoints[
                                (row - 1) * nodesPerRow + col - 1
                              ]?.description
                            }}
                          </div>
                        </div>
                        <!-- 水平连接线 -->
                        <div
                          v-if="
                            col < nodesPerRow &&
                            (row - 1) * nodesPerRow + col <
                              interventionPoints.length
                          "
                          class="timeline-connector horizontal"
                        ></div>
                      </div>
                      <!-- 空占位符 -->
                      <div v-else class="timeline-node-placeholder"></div>
                    </template>
                  </div>
                  <!-- 垂直连接线（行与行之间） -->
                  <div
                    v-if="
                      row < Math.ceil(interventionPoints.length / nodesPerRow)
                    "
                    class="timeline-vertical-connector"
                    :class="{
                      'connector-left': (row - 1) % 2 === 0,
                      'connector-right': (row - 1) % 2 === 1,
                    }"
                  ></div>
                </template>
              </div>
            </div>
          </Tabs.TabPane>
          <Tabs.TabPane key="patient-profile" tab="患者档案"
            >内容开发中...</Tabs.TabPane
          >
          <Tabs.TabPane key="management-plan" tab="管理方案"
            >内容开发中...</Tabs.TabPane
          >
          <Tabs.TabPane key="intervention-management" tab="干预管理"
            >内容开发中...</Tabs.TabPane
          >
          <Tabs.TabPane key="follow-up-management" tab="随访管理"
            >内容开发中...</Tabs.TabPane
          >
          <Tabs.TabPane key="periodic-data" tab="周期数据"
            >内容开发中...</Tabs.TabPane
          >
        </Tabs>
      </Card>
    </div>
  </Page>
</template>

<style scoped>
.card-extra-link {
  padding: 2px 8px;
  border-radius: 4px;
  transition: background-color 0.3s;
}
.card-extra-link:hover {
  background-color: v-bind('token.controlItemBgHover');
}

.intervention-list-wrapper {
  height: 150px;
  overflow: hidden;
}
.intervention-list {
  list-style: none;
  padding: 0;
  margin: 0;
}
.intervention-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 6px 0;
}
.intervention-item .date {
  font-size: 12px;
  color: v-bind('token.colorTextSecondary');
}

/* 蛇形轨道时间线样式 */
.timeline-container {
  padding: 20px;
  width: 100%;
}

.timeline-track {
  display: flex;
  flex-direction: column;
  gap: 20px;
  width: 100%;
}

.timeline-row {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 16px;
  width: 100%;
  position: relative;
}

.timeline-row.row-reverse {
  flex-direction: row-reverse;
}

.timeline-node {
  flex: 1;
  max-width: 220px;
  min-width: 180px;
  position: relative;
  transition: all 0.3s ease;
  opacity: 0;
  animation: fadeIn 0.5s ease forwards;
}

@keyframes fadeIn {
  to {
    opacity: 1;
  }
}

.timeline-node:hover {
  transform: translateY(-5px);
}

.timeline-node-placeholder {
  flex: 1;
  max-width: 220px;
  min-width: 180px;
}

.timeline-card {
  background: v-bind('token.colorBgContainer');
  border: 2px solid v-bind('token.colorBorder');
  border-radius: 12px;
  padding: 16px 16px 16px 50px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
  width: 100%;
  min-height: 120px;
}

.timeline-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 4px;
  height: 100%;
  background: linear-gradient(
    180deg,
    v-bind('token.colorPrimary'),
    v-bind('token.colorPrimaryHover')
  );
}

.timeline-number {
  position: absolute;
  top: 12px;
  left: 12px;
  width: 24px;
  height: 24px;
  background: v-bind('token.colorPrimary');
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: bold;
  z-index: 3;
}

.timeline-node:hover .timeline-card {
  border-color: v-bind('token.colorPrimary');
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}

.timeline-date {
  font-size: 12px;
  color: v-bind('token.colorTextSecondary');
  margin-bottom: 8px;
  font-weight: 500;
}

.timeline-title {
  font-size: 14px;
  font-weight: 600;
  color: v-bind('token.colorText');
  margin-bottom: 8px;
  line-height: 1.4;
}

.timeline-content {
  font-size: 12px;
  color: v-bind('token.colorTextSecondary');
  line-height: 1.5;
  white-space: pre-line;
}

/* 连接线样式 */
.timeline-connector {
  position: absolute;
  background: v-bind('token.colorPrimary');
  z-index: 1;
}

/* 水平连接线 */
.timeline-connector.horizontal {
  top: 50%;
  right: -24px;
  width: 16px;
  height: 4px;
  transform: translateY(-50%);
  border-radius: 2px;
}

/* 垂直连接线（行与行之间的转弯） */
.timeline-vertical-connector {
  height: 20px;
  width: 4px;
  background: v-bind('token.colorPrimary');
  border-radius: 2px;
  position: relative;
}

.timeline-vertical-connector.connector-right {
  align-self: flex-end;
  margin-right: 8px;
}

.timeline-vertical-connector.connector-left {
  align-self: flex-start;
  margin-left: 8px;
}

/* 添加转弯指示器 */
.timeline-vertical-connector::before {
  content: '';
  position: absolute;
  width: 8px;
  height: 8px;
  background: v-bind('token.colorPrimary');
  border-radius: 50%;
  top: 50%;
  transform: translateY(-50%);
}

.timeline-vertical-connector.connector-right::before {
  right: -6px;
}

.timeline-vertical-connector.connector-left::before {
  left: -6px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .timeline-node {
    min-width: 160px;
    max-width: 200px;
  }

  .timeline-node-placeholder {
    min-width: 160px;
    max-width: 200px;
  }

  .timeline-row {
    gap: 12px;
  }
}

@media (max-width: 768px) {
  .timeline-container {
    padding: 10px;
  }

  .timeline-row {
    flex-direction: column;
    gap: 16px;
  }

  .timeline-row.row-reverse {
    flex-direction: column;
  }

  .timeline-node {
    max-width: none;
    min-width: auto;
  }

  .timeline-node-placeholder {
    display: none;
  }

  .timeline-connector {
    display: none;
  }

  .timeline-vertical-connector {
    display: none;
  }
}
</style>
